package zucc.edu.cn.chengchengparttime.Home;

import android.app.Fragment;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import zucc.edu.cn.chengchengparttime.Home.HomeAdapter;
import zucc.edu.cn.chengchengparttime.LoginAndReg.LoginActivity;
import zucc.edu.cn.chengchengparttime.MainActivity;
import zucc.edu.cn.chengchengparttime.R;
import zucc.edu.cn.chengchengparttime.Text;
import zucc.edu.cn.chengchengparttime.Work;
import zucc.edu.cn.chengchengparttime.dbHomeHelper;

public class HomeFragment extends Fragment {
    private static final String DEBUG_TAG="Chengcheng Log2";
    private SQLiteDatabase mDatabase;// 数据库实例

    private RecyclerView rv; //RecyclerView布局
    private HomeAdapter homeAdapter; //适配器
    private Context context;
    private List<Work> data=new ArrayList<>(); //数据列表
    private EditText editText;
    private TextView search;
    private MyBroadcast myBroadcast;

    private String type="";

    public HomeFragment() {}

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        context = this.getActivity();
        rv = view.findViewById(R.id.rv);

        mDatabase=SQLiteDatabase.openDatabase("/data/user/0/zucc.edu.cn.chengchengparttime/databases/Chengcheng.db",null,SQLiteDatabase.OPEN_READWRITE);//获取数据库
        Log.d("Chengcheng.db2","获取数据库"+mDatabase);

        loadwork(mDatabase,view,"");//一开始加载所有兼职
//        loadwork(mDatabase,view,"学生助理");

        editText=view.findViewById(R.id.search);
        editText.setOnClickListener(view1 -> {
            Toast.makeText(this.context, "点击了搜索兼职输入框" , Toast.LENGTH_SHORT).show();
        });

        search=view.findViewById(R.id.textsearch);
        search.setOnClickListener(view1 -> {
            Toast.makeText(this.context, "点击了搜索兼职" , Toast.LENGTH_SHORT).show();
            //关闭手机的键盘
            InputMethodManager imm=(InputMethodManager) view1.getContext().
                    getSystemService(Context.INPUT_METHOD_SERVICE);
            if (imm.isActive()) {
                imm.hideSoftInputFromWindow(view1.getApplicationWindowToken(),0 );
            }

            editText.setText("");
        });

        //下拉框的广播
        myBroadcast=new MyBroadcast();
        IntentFilter intentFilter=new IntentFilter();
        intentFilter.addAction("");
        intentFilter.addAction("讲解员");
        intentFilter.addAction("服务员");
        intentFilter.addAction("学生助理");
        intentFilter.addAction("助教");
        intentFilter.addAction("军训助理");
        intentFilter.addAction("体测工作人员");
        LocalBroadcastManager.getInstance(getContext()).registerReceiver(myBroadcast,intentFilter);
        return view;
    }

    public void loadwork(SQLiteDatabase mDatabase,View view,String type){
        //查询兼职信息表的记录
        if(type.length()!=0) { //有选择兼职种类
            data.clear();
            Cursor c = mDatabase.query("tbl_work", null, "WorkSerials=?", new String[]{type + ""}, null, null, null);
            c.moveToFirst();//游标移到第一条记录
            // 打印记录
            String[] x2 = new String[30];
            while (!c.isAfterLast()) {
                String rowResults = "||";
                for (int i = 0; i < c.getColumnCount(); i++) {
                    rowResults = rowResults.concat(c.getString(i) + "||");
                    x2[i] = c.getString(i);
                }
                Work work = new Work(Long.parseLong(x2[0]), x2[1], x2[2], x2[3], x2[4], x2[5], Double.parseDouble(x2[6]), x2[7], x2[8], x2[9], Integer.parseInt(x2[10]));
                data.add(work);
                Log.d("work", work.toString());//测试

                c.moveToNext();
            }
            Log.d(DEBUG_TAG, "查询成功");
            c.close();//关闭游标工厂

            //适配器的定义与设置
            homeAdapter = new HomeAdapter(data, context, view, mDatabase);
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this.getActivity());
            linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
            rv.setLayoutManager(linearLayoutManager);
            rv.setAdapter(homeAdapter);
        }else { //未选择兼职种类
            data.clear();
            //从用户表读取用户的意向兼职
            Cursor c2=mDatabase.query("tbl_user", null, "UserID=?",
                    new String[]{LoginActivity.getCurrentUser()}, null, null,null);
            c2.moveToFirst();//游标移到第一条记录
            // 打印记录
            String[] x3 = new String[30];
            while(!c2.isAfterLast()){
                String rowResults2 = "||";
                for (int i = 0; i < c2.getColumnCount(); i++) {
                    rowResults2 = rowResults2.concat(c2.getString(i) + "||");
                    x3[i]=c2.getString(i);
                }
                c2.moveToNext();
            }
            Log.d(DEBUG_TAG,"查询成功");
            c2.close();//关闭游标工厂

            //获得意向兼职1和意向兼职2
            String type1=x3[7]; //意向兼职1
            String type2=x3[8]; //意向兼职2

            //将意向兼职1先取出来
            if(type1!=null && !type1.equals("")){
                Cursor c3=mDatabase.query("tbl_work", null, "WorkSerials=?",
                        new String[]{type1}, null, null,null);
                c3.moveToFirst();//游标移到第一条记录
                // 打印记录
                String[] x4 = new String[30];
                while(!c3.isAfterLast()){
                    String rowResults3 = "||";
                    for (int i = 0; i < c3.getColumnCount(); i++) {
                        rowResults3 = rowResults3.concat(c3.getString(i) + "||");
                        x4[i]=c3.getString(i);
                    }
                    Work work=new Work(Long.parseLong(x4[0]),x4[1],x4[2],x4[3],x4[4],x4[5],
                            Double.parseDouble(x4[6]),x4[7],x4[8],x4[9],Integer.parseInt(x4[10]));
                    data.add(work);
                    c3.moveToNext();
                }
                Log.d(DEBUG_TAG,"查询成功");
                c3.close();//关闭游标工厂
            }

            //将意向兼职2取出来
            if(type2!=null && !type2.equals("")){
                Cursor c3=mDatabase.query("tbl_work", null, "WorkSerials=?",
                        new String[]{type2}, null, null,null);
                c3.moveToFirst();//游标移到第一条记录
                // 打印记录
                String[] x4 = new String[30];
                while(!c3.isAfterLast()){
                    String rowResults3 = "||";
                    for (int i = 0; i < c3.getColumnCount(); i++) {
                        rowResults3 = rowResults3.concat(c3.getString(i) + "||");
                        x4[i]=c3.getString(i);
                    }
                    Work work=new Work(Long.parseLong(x4[0]),x4[1],x4[2],x4[3],x4[4],x4[5],
                            Double.parseDouble(x4[6]),x4[7],x4[8],x4[9],Integer.parseInt(x4[10]));
                    data.add(work);
                    c3.moveToNext();
                }
                Log.d(DEBUG_TAG,"查询成功");
                c3.close();//关闭游标工厂
            }

            //显示兼职
            Cursor c=mDatabase.query("tbl_work", null, "WorkSerials!=? and WorkSerials!=?",
                    new String[]{type1,type2}, null, null,null);
            c.moveToFirst();//游标移到第一条记录
            // 打印记录
            String[] x2 = new String[30];
            while(!c.isAfterLast()){
                String rowResults = "||";
                for (int i = 0; i < c.getColumnCount(); i++) {
                    rowResults = rowResults.concat(c.getString(i) + "||");
                    x2[i]=c.getString(i);
                }
                Work work=new Work(Long.parseLong(x2[0]),x2[1],x2[2],x2[3],x2[4],x2[5],Double.parseDouble(x2[6]),x2[7],x2[8],x2[9],Integer.parseInt(x2[10]));
                data.add(work);
                Log.d("work",work.toString());//测试

                c.moveToNext();
            }
            Log.d(DEBUG_TAG,"查询成功");
            c.close();//关闭游标工厂

            //适配器的定义与设置
            homeAdapter=new HomeAdapter(data,context,view,mDatabase);
            LinearLayoutManager linearLayoutManager=new LinearLayoutManager(this.getActivity());
            linearLayoutManager.setOrientation(RecyclerView.VERTICAL);
            rv.setLayoutManager(linearLayoutManager);
            rv.setAdapter(homeAdapter);
        }
    }

    //广播
    private class MyBroadcast extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
            loadwork(mDatabase,getView(),intent.getAction());
        }
    }
}
